import React,  { Component } from 'react';
import axios from 'axios';
import cookie from 'react-cookies';
import MenuHead from '../comm/menuHead';
import Table from '../comm/table';
import TheDate from '../comm/theDate';
import '../comm/comm.css';

class Food extends Component {
  state = {
    cur_tab: "recommend",
    thead: [
        {en: 'record_date', ch: '日期'},
        {en: 'meal_type', ch: '类型'},
        {en: 'food_ratio', ch: '食物/比重'},
    ],
    tdata: [],
    theDate: "",
    meal_type: "",
    meal_type_list: ["", "早餐", "上午茶", "午餐", "下午茶", "晚餐", "夜宵"],
    food_list: [{id: 0, food: "", ratio: ""}],
    food_id_sqe: 0,
    first_food_id_sqe: 0,
    inputing_food_id: 0,
    food_type_list: [],
    search_food_type_list: [],
    query_begin_date: "",
    query_end_date: "",
    query_meal_type: "",
    record_count: 0,
    record_hits: 0,
    query_food: "",
    restart_query: false,
    isHideQueryCondition: true,
    food_input_read_only: false,
  }
  switchTab = (id) => {
    this.setState({
        cur_tab: id,
    })
  }
  getFoodItemIndex = (id) => {
    let tmp_list = [...this.state.food_list]
    for(let i = 0; i < tmp_list.length; i++) {
      if(id === tmp_list[i].id) {
        return i
      }
    }
    console.log(id)
    console.log(tmp_list)
    return 0
  }
  deleteFoodItem = (food_id) => {
    let tmp_food_list = this.state.food_list.filter(f => {
      return f.id !== food_id
    })
    this.setState({
      food_list: tmp_food_list
    })
  }
  addFoodItem = () => {
    let tmp_food_id_sqe = this.state.food_id_sqe + 1
    let tmp_food_item = {id: tmp_food_id_sqe, food: "", ratio: ""}
    let tmp_food_list = [...this.state.food_list, tmp_food_item]
    this.setState({
      food_list: tmp_food_list,
      food_id_sqe: tmp_food_id_sqe,
    })
  }
  batch_delete = (list) => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/delFood", {
        "record": list,
        "username": userName,
        "loginID": loginID,
    }).then((res) => {
        if("请先登录" === res.data.errorInfo) {
            this.props.history.push('/login');
        }
        if(true !== res.data.status){
          console.log(res.data)
        } else {
          this.clean_query_condition()
          setTimeout(() => {
            this.queryFood(0, 10)
          }, 1000)
        }
    }).catch((err) => {
        this.setState({error: "请求服务器端时产生的错误信息: " + err})
    })
  }
  modify_data = (data) => {
    let food_list = JSON.parse(data.food)
    for(let i = 0; i < food_list.length; i++){
      food_list[i].id = i
    }
    this.setState({
      theDate: data.record_date,
      meal_type: data.meal_type,
      food_list: food_list,
      food_id_sqe: 0,
      first_food_id_sqe: 0,
      food_input_read_only: true,
    })
    this.switchTab("input")
  }
  setTheDate = (date) => {
    this.setState({
      theDate: date
    })
  }
  queryFoodType = (food_type) => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/queryFoodType", {
        "name": food_type,
        "username": userName,
        "loginID": loginID,
    }).then((res) => {
        if("请先登录" === res.data.errorInfo) {
            this.props.history.push('/login');
        }
        let r_foodList = null === res.data.foodList ? [] : res.data.foodList
        this.setState({
          food_type_list: r_foodList
        })
    }).catch((err) => {
        this.setState({error: "请求服务器端时产生的错误信息: " + err})
    })
  }
  queryFood = (from, page) => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    if(this.state.restart_query){
      from = 0
      page = 10
    }
    axios.post("/app/queryFood", {
        "date": [this.state.query_begin_date, this.state.query_end_date],
        "from": from,
        "page": page,
        "size": 1000,
        "type": this.state.query_meal_type,
        "food": this.state.query_food,
        "username": userName,
        "loginID": loginID,
    }).then((res) => {
        if("请先登录" === res.data.errorInfo) {
            this.props.history.push('/login');
        }
        let r_data = null === res.data.data ? [] : res.data.data
        for(let i = 0; i < r_data.length; i++) {
          let food = JSON.parse(r_data[i].food)
          let food_ratio = ""
          for(let j = 0; j < food.length; j++) {
            food_ratio += food[j].food + ":" + food[j].ratio + ","
          }
          food_ratio = food_ratio.substring(0, food_ratio.length - 1)
          r_data[i].food_ratio = food_ratio
        }
        this.setState({
            tdata: r_data,
            record_count: res.data.count,
            record_hits: res.data.hits,
            restart_query: false,
        })
    }).catch((err) => {
        this.setState({error: "请求服务器端时产生的错误信息: " + err})
    })
  }
  meal_type_change = (e) => {
    this.setState({
      meal_type: e.target.value
    })
  }
  getCurStrDate = () => {
    let now = new Date()
    let year = now.getFullYear()
    let month = now.getMonth() + 1
    let day = now.getDate()
    let date = year + "-"
    if(month < 10) date += "0"
    date += month + "-"
    if(day < 10) date += "0"
    date += day
    return date
  }
  getSomeTime = (hh, mm) => {
    let now = new Date()
    now.setHours(hh)
    now.setMinutes(mm)
    return now
  }
  setDefaultType = () => {
    let now = new Date()
    let type = ""
    if(this.getSomeTime(5, 30) <= now && now <= this.getSomeTime(10, 0)) type = "早餐"
    else if(this.getSomeTime(10, 0) <= now && now <= this.getSomeTime(11, 30)) type = "上午茶"
    else if(this.getSomeTime(11, 30) <= now && now <= this.getSomeTime(14, 30)) type = "午餐"
    else if(this.getSomeTime(14, 30) <= now && now <= this.getSomeTime(17, 0)) type = "下午茶"
    else if(this.getSomeTime(17, 0) <= now && now <= this.getSomeTime(21, 0)) type = "晚餐"
    else type = "夜宵"
    this.setState({
      meal_type: type
    })
  }
  handleSubmit = () => {
    let food_list = this.state.food_list
    for(let i = 0; i < food_list.length; i++) {
      if("" === food_list[i].food) {
        alert("食物名不能为空")
        return
      }
      if("" === food_list[i].ratio) {
        alert("食物比重不能为空")
        return
      }
    }
    if("" === this.state.theDate){
      alert("日期不能为空")
      return
    }
    for(let i = 0; i < food_list.length; i++) {
      delete food_list[i]["id"]
    }
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/addFood", {
        "userName": userName,
        "loginID": loginID,
        "date": this.state.theDate,
        "type": this.state.meal_type,
        "food": food_list,
    }).then((res) => {
        if("请先登录" === res.data.errorInfo) {
            this.props.history.push('/login');
        }
        let tmp_food_id_sqe = this.state.food_id_sqe + 1
        this.setState({
          food_list: [{id: tmp_food_id_sqe, food: "", ratio: ""}],
          food_id_sqe: tmp_food_id_sqe,
          first_food_id_sqe: tmp_food_id_sqe,
        })
        this.clean_query_condition()
        setTimeout(() => {
          this.queryFood(0, 10)
          this.switchTab("query")
        }, 1000)
    }).catch((err) => {
        this.setState({error: "请求服务器端时产生的错误信息: " + err})
    })
  }
  food_edit = () => {
    this.setState({
      food_input_read_only: false,
    })
  }
  handleFoodTypeInput = (id, e) => {
    let tmp_food_list = this.state.food_list
    for(let i = 0; i < tmp_food_list.length; i++) {
      if(id === tmp_food_list[i].id) {
        tmp_food_list[i].food = e.target.value
      }
    }
    let food_type_list = [...this.state.food_type_list]
    let tmp_food_type_list = []
    for(let i = 0; i < food_type_list.length; i++) {
      if("" !== e.target.value &&
        -1 !== food_type_list[i].indexOf(e.target.value) &&
        food_type_list[i] !== e.target.value) {
        tmp_food_type_list.push(food_type_list[i])
      }
    }
    this.setState({
      food_list: tmp_food_list,
      search_food_type_list: tmp_food_type_list,
      inputing_food_id: id,
    })
  }
  handleFoodTypeSelect = (id, item) => {
    let tmp_food_list = this.state.food_list
    for(let i = 0; i < tmp_food_list.length; i++) {
      if(id === tmp_food_list[i].id) {
        tmp_food_list[i].food = item
      }
    }
    this.setState({
      food_list: tmp_food_list,
      search_food_type_list: [],
    })
  }
  isInt = (input) => {
    var reg = /^[1-9]+[0-9]*$/
    return reg.test(input) ? true : false
  }
  handleFoodRatioInput = (id, e) => {
    let tmp_food_list = this.state.food_list
    for(var i = 0; i < tmp_food_list.length; i++) {
      if(id === tmp_food_list[i].id) {
        if("" !== e.target.value && !this.isInt(e.target.value)) {
          e.target.value = ""
          alert("请输入整数")
        }
        tmp_food_list[i].ratio = e.target.value
      }
    }
    this.setState({
      food_list: tmp_food_list
    })
  }
  set_query_begin_date = (date) => {
    this.setState({
      query_begin_date: date,
      restart_query: true,
    })
  }
  set_query_end_date = (date) => {
    this.setState({
      query_end_date: date,
      restart_query: true,
    })
  }
  set_query_meal_type = (e) => {
    this.setState({
      query_meal_type: e.target.value,
      restart_query: true,
    })
  }
  set_query_food = (e) => {
    this.setState({
      query_food: e.target.value,
      restart_query: true,
    })
  }
  clean_query_condition = () => {
    this.setState({
      query_begin_date: "",
      query_end_date: "",
      query_meal_type: "",
      query_food: "",
      restart_query: true,
    })
  }
  HideOrShowQueryCondition = () => {
    this.setState({
      isHideQueryCondition: !this.state.isHideQueryCondition
    })
  }
  componentDidMount() {
    this.queryFoodType("")
    this.queryFood(0, 10)
    this.setState({
      theDate: this.getCurStrDate()
    })
    this.setDefaultType()
  }
  render(){
    let isRecommendShow = this.state.cur_tab === "recommend" ? "block" : "none";
    let isInputShow = this.state.cur_tab === "input" ? "block" : "none";
    let isQueryShow = this.state.cur_tab === "query" ? "block" : "none";

    let recommendStyle = this.state.cur_tab === "recommend" ? "#99d9ea" : "#f7f7f7";
    let inputStyle = this.state.cur_tab === "input" ? "#99d9ea" : "#f7f7f7";
    let queryStyle = this.state.cur_tab === "query" ? "#99d9ea" : "#f7f7f7";

    const food_list = this.state.food_list.map(f => {
      return (
        <tr key={f.id}>
          <td></td>
          <td>
            <input
              onChange={(e) => this.handleFoodTypeInput(f.id, e)}
              value={this.state.food_list[this.getFoodItemIndex(f.id)].food}
              readOnly={this.state.food_input_read_only}
              type="text" size="20" maxLength="20"></input>
            <ul className={'ulStyle'}>
              {this.state.inputing_food_id === f.id ? this.state.search_food_type_list.map((item, key) => {
                return <li
                  className={'liStyle'}
                  key={key}
                  onClick={() => this.handleFoodTypeSelect(f.id, item)}>{item}</li>
              }) : <div></div>}
            </ul>
          </td>
          <td></td>
          <td>
            <input
              onChange={(e) => this.handleFoodRatioInput(f.id, e)}
              value={this.state.food_list[this.getFoodItemIndex(f.id)].ratio}
              readOnly={this.state.food_input_read_only}
              type="text" size="5" maxLength="5"></input>
          </td>
          {this.state.first_food_id_sqe === f.id ?
            <td><span></span></td> :
            <td>
              { !this.state.food_input_read_only ?
                <span onClick={() => this.deleteFoodItem(f.id)} style={{background: `#f7f7f7`}}>删除</span> : <div></div>}
            </td>}
        </tr>
      )
    })

    const meal_type_list = this.state.meal_type_list.map(m => {
      return <option value={m} key={m}>{m}</option>
    })

    return(
      <div align="center">
        <MenuHead/>
        <h4>饮食助手</h4>
        <div>
          <table>
          <tbody>
          <tr>
            <td><span style={{background: `${recommendStyle}`}} onClick={() => this.switchTab("recommend")}>推荐</span></td>
            <td width='5'></td>
            <td><span style={{background: `${inputStyle}`}} onClick={() => this.switchTab("input")}>录入</span></td>
            <td width='5'></td>
            <td><span style={{background: `${queryStyle}`}} onClick={() => this.switchTab("query")}>查看</span></td>
            <td width='100'></td>
          </tr>
          </tbody>
          </table>
        </div>
        <br/>
          <div style={{display: `${isRecommendShow}`}}>
          recommend
          </div>
          <div style={{display: `${isInputShow}`}}>
            <table>
            <tbody>
            <tr>
              <td>日期：</td>
              <td><TheDate defautlDate={this.state.theDate} setDate={this.setTheDate} /></td>
              <td>类型：</td>
              <td>
                <select value={this.state.meal_type} onChange={e => this.meal_type_change(e)}>
                    { this.state.meal_type_list.map(m => {
                        if("" !== m){
                          return <option value={m} key={m}>{m}</option>
                        }
                        return ""
                      }) }
                </select>
              </td>
            </tr>
            </tbody>
            </table>
            <span>-----------------------------------------</span>
            <table>
            <tbody>
            <tr>
              <td></td>
              <td>食物：</td>
              <td></td>
              <td>比重：</td>
              <td>
                { !this.state.food_input_read_only ?
                  <span onClick={this.addFoodItem} style={{background: `#99d9ea`}}>添加</span> : <div></div>}
              </td>
            </tr>
            { food_list }
            <tr>
              <td></td>
              <td>
                { !this.state.food_input_read_only ? <button onClick={this.handleSubmit}>提交</button> : <div></div>}
              </td>
              <td></td>
              <td>
                { this.state.food_input_read_only ? <button onClick={this.food_edit}>编辑</button> : <div></div>}
              </td>
              <td></td>
            </tr>
            </tbody>
            </table>
          </div>
          <div style={{display: `${isQueryShow}`}}>
            { true !== this.state.isHideQueryCondition ?
              <div>
              <table>
              <tbody>
              <tr>
                <td>日期：</td>
                <td><TheDate
                  defautlDate={this.state.query_begin_date}
                  setDate={this.set_query_begin_date} /></td>
                <td>至</td>
              </tr>
              <tr>
                <td></td>
                <td><TheDate
                  defautlDate={this.state.query_end_date}
                  setDate={this.set_query_end_date} /></td>
                <td></td>
              </tr>
              </tbody>
              </table>
              <table>
              <tbody>
              <tr>
                <td>食物：</td>
                <td>
                  <input
                    value={this.state.query_food}
                    onChange={this.set_query_food}
                    type="text" size="20" maxLength="20"></input>
                </td>
              </tr>
              </tbody>
              </table>
              <table>
              <tbody>
              <tr>
                <td>类型：</td>
                <td>
                  <select value={this.state.query_meal_type} onChange={this.set_query_meal_type}>
                    { meal_type_list }
                  </select>
                </td>
                <td><button onClick={this.clean_query_condition}>清除</button></td>
              </tr>
              </tbody>
              </table>
              </div> : <div></div>}
              <button
                onClick={this.HideOrShowQueryCondition}>
                  {true === this.state.isHideQueryCondition ? "显示" : "隐藏"}查询条件</button>
            <Table
              head={this.state.thead}
              data={this.state.tdata}
              queryData={this.queryFood}
              deleteData={this.batch_delete}
              modifyData={this.modify_data}
              recordCount={this.state.record_count}
              recordHits={this.state.record_hits}
              restartQuery = {this.state.restart_query} />
          </div>
      </div>
    )
  }
}

export default Food;
